package com.blog.scheduleTask;

import com.blog.enums.StaticVariable;
import com.blog.service.BlogService;
import com.blog.service.ViewService;
import com.blog.vo.DetailedBlog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author suoyue_zhan
 * @date 2021/02/04 19:38
 * @descript redis 文章阅读量 持久化到mysql
 */
@Component
@Configuration
@EnableScheduling
public class RedisToMysql {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlogService blogService;

    @Autowired
    private ViewService viewService;

    //redis的KEY值
    private String BLOG_NUM_KEYS = "blog_num:*";
    private String BLOG_DETAIL_KEYS = "blog_detail:*";

    //每天23:59:59执行一次将redis文章的访问量增量加入DB中
    @Scheduled(cron = "59 59 23 * * ?")
//    @Scheduled(cron = "0 0/2 16 * * ?")
    public void blogNumToSQL(){

        ValueOperations<String,Integer> operationNum = redisTemplate.opsForValue();
        ValueOperations<String, DetailedBlog> operations = redisTemplate.opsForValue();

        //存储有数据/要更新的key值
        List<String> blogKeyList = new ArrayList<>();
        Set<String> blogNumKeys = redisTemplate.keys(BLOG_NUM_KEYS);
        for(String key : blogNumKeys){
            blogKeyList.add(key);
            Integer views = operationNum.get(key);
//            viewTotal += views;     //日访问总量
            //文章ID
            String strId = key.substring(key.lastIndexOf(":")+2,key.length());

            //mysqlg根据strId更新/增加文章阅读量view
            blogService.updateView(Long.parseLong(strId),views);

            /**
             * 更新redis缓存的文章访问量
             */
            String reKey = StaticVariable.blogDetail + strId;
            DetailedBlog detailedBlog = operations.get(reKey);
            detailedBlog.setViews(detailedBlog.getViews()+views);
            operations.set(reKey,detailedBlog);
        }
        //redis删除缓存增加的阅读量数据
        redisTemplate.delete(blogNumKeys);
    }


    //一周执行一次－将文章内容刷到redis里
    @Scheduled(fixedDelay = 604800000)
    public void blogToRedis() {
        ValueOperations<String, DetailedBlog> operations = redisTemplate.opsForValue();
        List<DetailedBlog> detailedBlogList = blogService.getAllDetailedBlog();
        for (DetailedBlog detailedBlog : detailedBlogList) {
            String key = StaticVariable.blogDetail + detailedBlog.getId();
            operations.set(key,detailedBlog);
        }
    }

}
